import { Route } from '@ant-design/pro-layout/es/typing';
import lodash from 'lodash';
import { utils } from '../utils';
import convertToUmiRoutes from './convertToUmiRoutes';
import { SfwMicroApp, SfwRoute } from './sfwTypes';

/**
 * 有权限的路由
 *
 * https://umijs.org/zh-CN/plugins/plugin-layout#%E6%89%A9%E5%B1%95%E7%9A%84%E8%B7%AF%E7%94%B1%E9%85%8D%E7%BD%AE
 *
 * @param options
 */
export default function authorizedMenus(options: {
  routes?: SfwRoute[];
  predicate?: (app: SfwMicroApp) => boolean;
  addAppName?: boolean;
}): Route[] {
  const { routes, predicate, addAppName } = options;
  const umiRoutes = lodash.sortBy(
    convertToUmiRoutes(routes || [], addAppName),
    ['sequence'],
  );

  let filterRoutes = !predicate
    ? umiRoutes
    : umiRoutes.filter((it: any) => predicate(it));
  const removeAppRoutes = filterRoutes.map((it) => lodash.omit(it, 'app'));
  return utils.arrayToTree<Route>(
    removeAppRoutes,
    'code',
    'parentCode',
  ) as Route[];
}
